package com.zidian.teacher.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;

import com.google.gson.Gson;
import com.zidian.teacher.R;
import com.zidian.teacher.adapter.TeachingWorkAdapter;
import com.zidian.teacher.bean.WorkListBean;
import com.zidian.teacher.common.Constant;
import com.zidian.teacher.utils.GetUserInfo;
import com.zidian.teacher.utils.ToastUtil;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import okhttp3.Call;

import com.zidian.teacher.common.ToolBarActivity;

/**
 * Created by Administrator on 2016/9/5 0005.
 */
public class TeachingWorkListActivity extends ToolBarActivity {


    public SwipeRefreshLayout mSwipeRefreshWidget;
    private RecyclerView mRecyclerView;

    private ImageButton workAdd;


    boolean isLoading = true;
    private List<WorkListBean.DataBean> data = new ArrayList<>();
    private TeachingWorkAdapter adapter;
    private Handler handler = new Handler();
    private int startrow = 1;
    private String workName = "";
    private boolean isRefreshing = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setToolbarView(R.layout.toolbar_add);
        setContentView(R.layout.activity_teaching_work);
        setTitle("作业管理");

        workAdd = (ImageButton) findViewById(R.id.toolbar_add);

        adapter = new TeachingWorkAdapter(this, data);
        mSwipeRefreshWidget = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_widget);
        mRecyclerView = (RecyclerView) findViewById(R.id.list);
        initView();
        initData();
    }

    public void initView() {

        mSwipeRefreshWidget.setColorSchemeResources(R.color.colorAccent);

        mSwipeRefreshWidget.post(new Runnable() {
            @Override
            public void run() {
                mSwipeRefreshWidget.setRefreshing(true);
                isRefreshing = true;
            }
        });
        mSwipeRefreshWidget.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        data.clear();
                        startrow = 1;
                        workName = "";
                        isRefreshing = true;
                        getWorkList(startrow + "", workName);
                    }
                }, 2000);
            }
        });
        mRecyclerView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (isRefreshing) {
                    return true;
                } else {
                    return false;
                }
            }
        });

        final LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.setAdapter(adapter);
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                Log.d("test", "StateChanged = " + newState);


            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                Log.d("test", "onScrolled");

                int lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();
                if (lastVisibleItemPosition + 1 == adapter.getItemCount()) {
                    Log.d("test", "loading executed");

                    boolean isRefreshing = mSwipeRefreshWidget.isRefreshing();
                    if (isRefreshing) {
                        adapter.notifyItemRemoved(adapter.getItemCount());
                        return;
                    }
                    if (!isLoading) {
                        isLoading = true;
                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                startrow++;
                                getWorkList(startrow + "", workName);
                                Log.d("test", "load more completed");
                                isLoading = false;
                            }
                        }, 1000);
                    }
                }
            }
        });


        //添加点击事件
        adapter.setOnItemClickListener(new TeachingWorkAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Log.d("test", "item position = " + position);
//                startActivity(InteractionAskDetailAct.class);
            }

            @Override
            public void onItemLongClick(View view, int position) {

            }
        });

        adapter.setOnSearchClick(new TeachingWorkAdapter.OnSearchClick() {
            @Override
            public void onSearchClick(LinearLayout searchLin, LinearLayout searchEditLin, EditText edit) {
                searchEditLin.setVisibility(View.GONE);
                searchLin.setVisibility(View.VISIBLE);
                // 获取编辑框焦点
                edit.setFocusable(true);

                //打开软键盘
                InputMethodManager imm = (InputMethodManager) TeachingWorkListActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                ToastUtil.showToast(context, edit.getText().toString().trim());
                if (edit.getText().toString().trim().length() == 0) {
                    workName = "";
                } else {
                    workName = edit.getText().toString().trim();
                }
                data.clear();
                startrow = 1;
                getWorkList(startrow + "", workName);

            }
        });

        workAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent();
                intent.setClass(context, TeachingWorkAddActivity.class);
                startActivityForResult(intent, 4000);
            }
        });

    }

    public void initData() {
        startrow = 1;
        workName = "";
        getWorkList(startrow + "", workName);
    }

    /**
     * 获取测试数据
     */
    private void getData(List<WorkListBean.DataBean> model) {

//        for (int i = 0; i < 6; i++) {
//            Map<String, Object> map = new HashMap<>();
//            data.add(map);
//        }
        data.addAll(model);
        adapter.notifyDataSetChanged();
        mSwipeRefreshWidget.setRefreshing(false);
        adapter.notifyItemRemoved(adapter.getItemCount());
    }

    private void getWorkList(String startrow, String workName) {

        String loginUrl = Constant.URL_GOAL + "work/select";
        HashMap<String, String> map = new HashMap<>();
        map.put("startrow", startrow);
        map.put("pageSize", "10");
        map.put("teacherId", GetUserInfo.getTeacherId(context));
        map.put("workName", workName);
        map.put("token", GetUserInfo.getToken(context));


        OkHttpUtils.post().url(loginUrl).params(map).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {

                ToastUtil.showToast(context, "获取列表失败！");
                mSwipeRefreshWidget.setRefreshing(false);
                isRefreshing = false;
            }

            @Override
            public void onResponse(String response, int id) {
                mSwipeRefreshWidget.setRefreshing(false);
                isRefreshing = false;
                Log.e("T", response);
                try {
                    JSONObject jsonObject = null;
                    jsonObject = new JSONObject(response);
                    int resultCode = jsonObject.getInt("code");

                    if (resultCode != 200) {
                        ToastUtil.showToast(context, jsonObject.getString("message"));
                        isLoading = true;
                        adapter.setMore(false);
                        adapter.notifyItemRemoved(adapter.getItemCount());
                        return;
                    }

                } catch (JSONException e) {

                }

                Gson gson = new Gson();
                WorkListBean model = gson.fromJson(response, WorkListBean.class);
                if (model.isSuccess()) {
                    if (model.getData().size() < 10) {
                        isLoading = true;
                        adapter.setMore(false);
                    } else {
                        isLoading = false;
                        adapter.setMore(true);
                    }
                    getData(model.getData());
                }

            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);

        if (requestCode == 4000) {
            if (resultCode == 4001) {
                boolean hasChange = intent.getBooleanExtra("hasChange", false);
                if (hasChange) {
                    data.clear();
                    startrow = 1;
                    workName = "";
                    getWorkList(startrow + "", workName);
                }
            }
        }

    }
}
